<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/9/17
 * Time: 14:02
 */
namespace App\Api\Controllers\DaDa;


use App\Models\DadaConfig;
use App\Models\DadaMerchant;
use App\Models\DadaOrder;
use App\Models\DadaStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class SelectController extends BaseController
{
    /**
     * 达达平台-获取城市信息列表
     * @param Request $request
     * @return string
     */
    public function cityCodeList(Request $request)
    {
        $config_id = $request->post('configId', '1234'); //服务商配置id,不传走平台，1234

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_store_obj = DadaMerchant::where('config_id', $config_id)
            ->where('status', 1)
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建or状态异常'
            ]);
        }

        $is_city_list = Cache::has('dadaCityCodeList');
        if ($is_city_list) {
            $city_list = Cache::get('dadaCityCodeList');
            if ($city_list) {
                return json_encode([
                    'status' => '1',
                    'data' => $city_list,
                    'message' => '成功'
                ]);
            }
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_store_obj->source_id;

        try {
//            Log::info('达达配送-获取城市信息列表');
            $res_arr = $this->http_post($this->city_code_list, $app_key, $app_secret, $source_id); //1-成功 2-失败
//            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    Cache::put('dadaCityCodeList', $result_arr['result'], 100000);
//                    Log::info($result_arr['result']);
                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 达达平台-获取取消原因
     * @param Request $request
     * @return string
     */
    public function orderCancelReasons(Request $request)
    {
        $config_id = $request->post('configId', '1234'); //服务商配置id,不传走平台，1234
        $store_id = $request->post('storeId', ''); //门店id

//        $check_data = [
//            'storeId' => '门店id'
//        ];
//        $check = $this->check_required($request->except(['token']), $check_data);
//        if ($check) {
//            return json_encode([
//                'status' => '2',
//                'message' => $check
//            ]);
//        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_store_obj = DadaMerchant::where('config_id', $config_id)
            ->where('status', 1)
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建or状态异常'
            ]);
        }

        $is_cancel_reasons = Cache::has('dadaCancelReasons');
        if ($is_cancel_reasons) {
            $cancelReasonsList = Cache::get('dadaCancelReasons');
            if ($cancelReasonsList) {
                return json_encode([
                    'status' => '1',
                    'data' => $cancelReasonsList,
                    'message' => '成功'
                ]);
            }
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_store_obj->source_id;

        try {
            Log::info('达达配送-获取取消原因');
            $res_arr = $this->http_post($this->order_cancel_reasons, $app_key, $app_secret, $source_id); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    Cache::put('dadaCancelReasons', $result_arr['result'], 100000);

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 达达平台-订单详情查询
     * @param Request $request
     * @return string
     */
    public function orderStatusQuery(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id,不传走平台，1234
        $store_id = $request->post('storeId', ''); //门店id
        $order_id = $request->post('orderId', ''); //第三方订单编号

        $check_data = [
//            'storeId' => '门店id',
            'orderId' => '第三方订单编号'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_store_obj = DadaMerchant::where('config_id', $config_id)
            ->where('status', 1)
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_store_obj->source_id;

        try {
            $requestData = [
                'order_id' => $order_id
            ];
            Log::info('达达配送-订单详情查询');
            $res_arr = $this->http_post($this->status_query, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'status_code' => $result_arr['result']['statusCode'],
                        'status_msg' => $result_arr['result']['statusMsg']
                    ];
                    if (isset($result_arr['result']['transporterName'])) $update_data['transporter_name'] = $result_arr['result']['transporterName'];
                    if (isset($result_arr['result']['transporterPhone'])) $update_data['transporter_phone'] = $result_arr['result']['transporterPhone'];
                    if (isset($result_arr['result']['transporterLng'])) $update_data['transporter_lng'] = $result_arr['result']['transporterLng'];
                    if (isset($result_arr['result']['transporterLat'])) $update_data['transporter_lat'] = $result_arr['result']['transporterLat'];
                    if (isset($result_arr['result']['deliveryFee'])) $update_data['delivery_fee'] = $result_arr['result']['deliveryFee'];
                    if (isset($result_arr['result']['tips'])) $update_data['tips'] = $result_arr['result']['tips'];
                    if (isset($result_arr['result']['couponFee'])) $update_data['coupon_fee'] = $result_arr['result']['couponFee'];
                    if (isset($result_arr['result']['insuranceFee'])) $update_data['insurance_fee'] = $result_arr['result']['insuranceFee'];
                    if (isset($result_arr['result']['actualFee'])) $update_data['actual_fee'] = $result_arr['result']['actualFee'];
                    if (isset($result_arr['result']['distance'])) $update_data['distance'] = $result_arr['result']['distance'];
                    if (isset($result_arr['result']['createTime'])) $update_data['create_time'] = $result_arr['result']['createTime'];
                    if (isset($result_arr['result']['acceptTime'])) $update_data['accept_time'] = $result_arr['result']['acceptTime'];
                    if (isset($result_arr['result']['fetchTime'])) $update_data['fetch_time'] = $result_arr['result']['fetchTime'];
                    if (isset($result_arr['result']['finishTime'])) $update_data['finish_time'] = $result_arr['result']['finishTime'];
                    if (isset($result_arr['result']['cancelTime'])) $update_data['cancel_time'] = $result_arr['result']['cancelTime'];
                    if (isset($result_arr['result']['orderFinishCode'])) $update_data['order_finish_code'] = $result_arr['result']['orderFinishCode'];
                    if (isset($result_arr['result']['deductFee'])) $update_data['deduct_fee'] = $result_arr['result']['deductFee'];

                    $dada_order_obj = DadaOrder::where('origin_id', $order_id)
                        ->first();
                    $result = $dada_order_obj->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '订单详情查询,更新订单失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 达达平台-门店详情
     *
     * @param Request $request
     * @return string
     */
    public function shopDetail(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id,不传走平台，1234
        $origin_shop_id = $request->post('originShopId', ''); //门店编码

        $check_data = [
            'originShopId' => '门店编码'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $dada_order_obj = DadaOrder::where('origin_shop_id', $origin_shop_id)->first();
        if (!$dada_order_obj) {
            return json_encode([
                'status' => '2',
                'message' => '门店详情,门店信息未找到'
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '门店详情,达达配送参数未配置'
            ]);
        }

        $dada_merchant_obj = DadaMerchant::where('config_id', $config_id)
            ->where('status', 1)
            ->first();
        if (!$dada_merchant_obj) {
            return json_encode([
                'status' => '2',
                'message' => '门店详情,达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_merchant_obj->source_id;

        try {
            $requestData = [
                'origin_shop_id' => $origin_shop_id
            ];
            Log::info('达达配送-门店详情');
            $res_arr = $this->http_post($this->shop_detail, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'status' => $result_arr['result']['status']
                    ];

                    $result = $dada_order_obj->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '门店详情,更新订单失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'] ?? [],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 系统达达订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dada_order_info(Request $request)
    {
        $token = $this->parseToken();
        $store_id = $request->post('storeId', ''); //门店id
        $origin_id = $request->post('originId', ''); //第三方订单ID
        $dada_order_id = $request->post('dadaOrderId', ''); //达达订单号

        $check_data = [
            'storeId' => '门店id'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            $this->status = 2;
            $this->message = $check;
            return $this->format();
        }

        try {
            $where = [];
            if ($origin_id) {
                $where[] = ['origin_id', $origin_id];
            }
            if ($dada_order_id) {
                $where[] = ['dada_order_id', $dada_order_id];
            }

            $dada_order_obj = DadaOrder::where($where)
                ->where('store_id', $store_id)
                ->get();
            if ($dada_order_obj) {
                $this->status = 1;
                $this->message = '查询成功';
                return $this->format($dada_order_obj);
            } else {
                $this->status = 2;
                $this->message = '查询失败';
                return $this->format($store_id);
            }
        } catch (\Exception $ex) {
            $this->status = -1;
            $this->message = $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine();
            return $this->format();
        }
    }



}
